/****************************************************************************************
 * Copyright (c) 2010~2012 All Rights Reserved by
 *  G-Net Integrated Service Co.,  Ltd. 
 ****************************************************************************************/
/**
 * @file DESEncryptUtil.java
 * @author wenhui.li
 * @date 2012-9-26 下午8:00:22 
 * Revision History 
 *     - 2012-9-26: change content for what reason
 ****************************************************************************************/
package com.openingedu.mba.util;

import java.security.SecureRandom;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import android.util.Log;

import com.openingedu.mba.common.CommonUtil;

/**
 * @brief DES加密解密工具类 功能描述： 主要提供数据DES加密解密
 */
public class DESEncrypt {

	private final static String DES = "DES"; // /<加密类型
	// DESKEY字节数
	private static final Integer DESKEY_BYTES_NUM = 8;

	/**
	 * @brief 生成DESKey(8位)
	 * @return DESKey
	 */
	public static String createDESkey() {
		Random random = new Random();
		int deskeyint = random.nextInt();
		String hexStr = Integer.toHexString(deskeyint);

		int length = hexStr.length();
		if (length < DESKEY_BYTES_NUM) {
			for (int i = 0; i < DESKEY_BYTES_NUM - length; i++) {
				hexStr = hexStr + 0;
			}
		}
		if (length > DESKEY_BYTES_NUM) {
			hexStr = hexStr.substring(0, hexStr.length()
					- (length - DESKEY_BYTES_NUM));
		}
		return hexStr;
	}

	/**
	 * @brief 对字符串参数加密
	 * @param value
	 *            需要加密的参数
	 * @return 加密后的字符串
	 */
	public static String encrypt(String desKey, String value) {
		if (CommonUtil.isNull(value))
			return "";

		Log.d("MM--->deskeyShared", "deskeyShared===" + desKey);

		try {
			return byte2hex(encrypt(value.getBytes("utf-8"),
					desKey.getBytes("utf-8")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @brief 对字符串参数解密
	 * @param data
	 *            需要解密数据
	 * @return 解密后的数据
	 */
	public static String decrypt(String desKey, String data) {
		if (CommonUtil.isNull(data))
			return "";
		String result = null;
		try {
			result = new String(decrypt(hex2byte(data.getBytes("utf-8")),
					desKey.getBytes("utf-8")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @brief 加密 数据
	 * @param src
	 *            数据源
	 * @param key
	 *            密钥，长度必须是8的倍数
	 * @return 返回加密后的数据
	 * @throws Exception
	 *             抛出的异常
	 */
	private static byte[] encrypt(byte[] src, byte[] key) throws Exception {
		// DES算法要求有一个可信任的随机数源
		SecureRandom sr = new SecureRandom();
		// 从原始密匙数据创建DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);
		// 创建一个密匙工厂，然后用它把DESKeySpec转换成
		// 一个SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		// Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance(DES);
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
		// 现在，获取数据并加密
		// 正式执行加密操作
		return cipher.doFinal(src);
	}

	/**
	 * @brief 解密
	 * @param src
	 *            数据源
	 * @param key
	 *            密钥，长度必须是8的倍数
	 * @return 返回解密后的原始数据
	 * @throws Exception
	 *             抛出的异常
	 */
	private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
		// DES算法要求有一个可信任的随机数源
		SecureRandom sr = new SecureRandom();
		// 从原始密匙数据创建一个DESKeySpec对象
		DESKeySpec dks = new DESKeySpec(key);
		// 创建一个密匙工厂，然后用它把DESKeySpec对象转换成
		// 一个SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance(DES);
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
		// 现在，获取数据并解密
		// 正式执行解密操作
		return cipher.doFinal(src);
	}

	/**
	 * @brief 二进制转字符串
	 * @param b
	 *            需要转换的二进制
	 * @return 返回转换后的字符串
	 */
	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	/**
	 * @brief 二进制转换为16进制
	 * @param b
	 *            需要转换的二进制
	 * @return 转换后的16进制
	 */
	private static byte[] hex2byte(byte[] b) {
		if ((b.length % 2) != 0)
			throw new IllegalArgumentException("长度不是偶数");
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	/**
	 * @brief 生成DESKey
	 * @param hexLength
	 *            desKey长度
	 * @return DESKey
	 */
	public static String createDESKey(int hexLength) {
		int deskeyint = (int) (new Random().nextInt());
		String hexString = Integer.toHexString(deskeyint);
		int length = hexString.length();
		if (length < hexLength) {
			for (int i = 0; i < hexLength - length; i++) {
				hexString = hexString + 0;
			}
		}
		if (length > hexLength) {
			hexString = hexString.substring(0,
					hexString.length() - (length - hexLength));
		}
		return hexString;
	}

	/**
	 * @brief 验证Key正确性
	 * @details -# key为6位16进制随机数+MD5加密串 -# 内网标识，比如：NW +
	 *          6位16进制随机数，内网标识是固定的，后边加的随机数与MD5加密串前的随机数是一样的
	 * 
	 * @param key
	 *            身份验证串
	 * @return true:key值正确; false:key值不正确
	 */
	@SuppressWarnings("unused")
	private boolean isValidKey(String key) {
		if (key.length() <= 10) {
			return false;
		} else {
			// 取得前6位随机数
			String random = key.substring(0, 6);
			String md5 = key.substring(6, key.length());
			String md5Key = "mba_";
			String tempMd5 = MD5.encryptHex(md5Key + random);
			return tempMd5.equals(md5);
		}
	}
}
